﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using OSVDB_TrayApp.Properties;
using System.Diagnostics;
using System.Globalization;
using OSVDB_TrayApp.Cultures;
using Microsoft.Win32;
using System.IO;
using IWshRuntimeLibrary;

namespace OSVDB_TrayApp
{
    /// <summary>
    /// Interaction logic for Settings.xaml
    /// </summary>
    public partial class Setting : Window
    {
        Settings MySettings;
        bool isSaved;
        bool isChanged;
        Window1 owner;
        bool firstopen = true;

        public Setting(Window1 owner)
        {
            this.WindowStartupLocation = WindowStartupLocation.CenterScreen;
            MySettings = Settings.Default;

            InitializeComponent();

            isSaved = false;

            this.grdSettings.DataContext = MySettings;

            MySettings.PropertyChanged +=new System.ComponentModel.PropertyChangedEventHandler(MySettings_PropertyChanged);

            this.owner = owner;

            CultureResources.ResourceProvider.DataChanged += new EventHandler(ResourceProvider_DataChanged);

            //Debug.WriteLine(string.Format("Set culture to default [{0}]:", Properties.Settings.Default.DefaultCulture));
            //CultureResources.ChangeCulture(Properties.Settings.Default.DefaultCulture);

            this.InitializeComponent();

            this.cbLanguages.SelectionChanged += new System.Windows.Controls.SelectionChangedEventHandler(this.cbLanguages_SelectionChanged);
            cbLanguages.SelectedItem = Properties.Settings.Default.DefaultCulture;

        }

        void ResourceProvider_DataChanged(object sender, EventArgs e)
        {
            //Debug.WriteLine(string.Format("ObjectDataProvider.DataChanged event. fetching culturename property for new culture [{0}]", Properties.Resources.LabelCultureName));
         }

        public Setting()
        {
            MySettings = Settings.Default;

            InitializeComponent();

            isSaved = false;

            this.grdSettings.DataContext = MySettings;

            MySettings.PropertyChanged += new System.ComponentModel.PropertyChangedEventHandler(MySettings_PropertyChanged);

            CultureResources.ResourceProvider.DataChanged += new EventHandler(ResourceProvider_DataChanged);

            Debug.WriteLine(string.Format("Set culture to default [{0}]:", Properties.Settings.Default.DefaultCulture));
            CultureResources.ChangeCulture(Properties.Settings.Default.DefaultCulture);

            this.InitializeComponent();

         this.cbLanguages.SelectionChanged += new System.Windows.Controls.SelectionChangedEventHandler(this.cbLanguages_SelectionChanged);
            cbLanguages.SelectedItem = Properties.Settings.Default.DefaultCulture;

        }

        private void cbLanguages_SelectionChanged(object sender, EventArgs e)
        {
            if (firstopen)
            {
                firstopen = false;
            }
            else
            {
                System.Windows.MessageBox.Show("You have to restart the program, to take advance of the chances.", "Please restart", MessageBoxButton.OK, MessageBoxImage.Information);
            }
        }

        private void Save_Click(object sender, RoutedEventArgs e)
        {
            if (this.txtApiKey.Text != "")
            {
                if (!checkForInt(this.txtRefresh.Text) && this.txtRefresh.Text != "")
                {
                    MessageBox.Show("Refresh interval must be a number.\nAll settings will be lost.", "Warning", MessageBoxButton.OK, MessageBoxImage.Warning);
                    MySettings.Reset();
                }
                else
                {
                    if (this.txtRefresh.Text == "")
                    {
                        MySettings.RefreshInterval = 15;
                    }
                    else
                    {
                        MySettings.RefreshInterval = Int32.Parse(this.txtRefresh.Text);
                    }
                    MySettings.ApiKey = this.txtApiKey.Text;
                    MySettings.GetMilw0rm = this.chkMil.IsChecked.Value;
                    MySettings.getPacketExpl = this.chkPacketStorm.IsChecked.Value;
                    MySettings.getPacketVulns = this.chkPacketVuln.IsChecked.Value;
                    MySettings.getSecFocus = this.chkSecFoc.IsChecked.Value;
                    MySettings.NotifyIfClosed = this.chkNotifyClosing.IsChecked.Value;
                    MySettings.NotifyOnNews = this.chkNotifyNews.IsChecked.Value;
                    MySettings.DefaultCulture = new CultureInfo(this.cbLanguages.SelectedValue.ToString());
                    MySettings.getWatchList = this.chkWatchList.IsChecked.Value;
                    MySettings.DoAutoStart = this.chkAutoStart.IsChecked.Value;

                    MySettings.Save();

                    if (this.owner != null)
                    {
                        this.owner.InitializeTimer();
                        this.owner.LoadFeeds();
                    }
                    firstopen = true;
                    this.Close();

                    if (this.chkWatchList.IsChecked.Value)
                    {
                        this.owner.tab_WatchList.Visibility = Visibility.Visible;
                    }
                    else
                    {
                        this.owner.tab_WatchList.Visibility = Visibility.Collapsed;
                    }

                    if(this.chkAutoStart.IsChecked.Value)
                    {
                        WshShellClass WshShell = new WshShellClass();

                        string startup = Environment.GetFolderPath(Environment.SpecialFolder.Startup);

                        IWshRuntimeLibrary.IWshShortcut MyShortcut = (IWshRuntimeLibrary.IWshShortcut)WshShell.CreateShortcut(startup + "\\OSVDB_TrayApp.lnk");

                        string loc = System.Reflection.Assembly.GetEntryAssembly().Location;

                        MyShortcut.TargetPath = loc;
                        MyShortcut.Description = "OSVDB: Vulnerability Updates";
                        MyShortcut.IconLocation = loc.Substring(0, loc.LastIndexOf("\\")) + @"\OSVDB_1616.ico";

                        MyShortcut.Save();
                    }
                    else
                    {
                        string startup = Environment.GetFolderPath(Environment.SpecialFolder.Startup) + "\\OSVDB_TrayApp.lnk";

                        if (System.IO.File.Exists(startup))
                        {
                            System.IO.File.Delete(startup);
                        }
                    }

                    MessageBox.Show("Settings successfully saved.", "Saving successful", MessageBoxButton.OK, MessageBoxImage.Information);
                    isSaved = true;
                }
            }
            else
            {
                MessageBox.Show("An apikey must be provided.\nAll settings will be lost.", "Warning", MessageBoxButton.OK, MessageBoxImage.Warning);
                MySettings.Reset();
            }
        }

        private bool checkForInt(String mystring)
        {
            try
            {
                Int32.Parse(mystring);
                return true;
            }
            catch (FormatException)
            {
                return false;
            }
        }

        

        private void Cancel_Click(object sender, RoutedEventArgs e)
        {
              
            if(!isSaved && isChanged)
            {
                MessageBoxResult result;

                result = MessageBox.Show("Really close Settings without saving?", "Save?", MessageBoxButton.YesNoCancel, MessageBoxImage.Question);

                if (result == MessageBoxResult.Yes)
                {
                    firstopen = true;
                    this.Close();
                }

                // else do nothing
            }
            else
            {
                this.Close();
            }
        }

        public void MySettings_PropertyChanged(object sender, EventArgs e)
        {
            this.isChanged = true;
        }
    }
}
